//
//  DownloadViewController.swift
//  DownloadTube
//
//  Created by Carlos on 07/10/14.
//  Copyright (c) 2014 Carlos. All rights reserved.
//

import UIKit
import AVFoundation
import AVKit

class DownloadViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource {

    let player:AVPlayerViewController = AVPlayerViewController()
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var clearCompletedDownloadsButton: UIBarButtonItem!
    @IBOutlet weak var cancelActiveDownloadsButton: UIBarButtonItem!
    
    override func viewDidLoad() {

        super.viewDidLoad()
        tableView.estimatedRowHeight = 110
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.emptyDataSetSource = self
        tableView.tableFooterView = UIView()
    }
   
    override func didReceiveMemoryWarning() {
        
        super.didReceiveMemoryWarning()
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
       
        return DownloadManager.sharedInstance.listDownloads().count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cellIndentifier: NSString = "DownloadCell"
        var cell: DownloadCell = tableView.dequeueReusableCellWithIdentifier(cellIndentifier) as DownloadCell
        let downloadTask = DownloadManager.sharedInstance.listDownloads()[indexPath.row]

        cell.title.text = downloadTask.video.title
        cell.author.text = downloadTask.video.author
        updateDownloadTaskCell(indexPath, downloadCell: cell)
        
        return cell
    }

    
    override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject!) -> Bool {

        if(identifier == "playDownloadedVideo") {
        
            let indexSelected = tableView.indexPathForSelectedRow()?.row
            var downloadTask = DownloadManager.sharedInstance.listDownloads()[indexSelected!]
        
            return downloadTask.isCompleted()
        }
        
        return false
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        
        let indexSelected = tableView.indexPathForSelectedRow()?.row
        var downloadTask = DownloadManager.sharedInstance.listDownloads()[indexSelected!]
 
        if(downloadTask.isCompleted()){

            let playerController:PlayerViewController = segue.destinationViewController as PlayerViewController
            playerController.file = downloadTask.videoFilename
        }
    }
    
    func tableView(tableView: UITableView!, editActionsForRowAtIndexPath indexPath: NSIndexPath!) -> [AnyObject] {
    
        let downloadTask = DownloadManager.sharedInstance.listDownloads()[indexPath.row]
        var actions:[AnyObject] = []
        
        if (downloadTask.isCompleted()) {
            
            let clearAction = UITableViewRowAction(style: .Default, title: Utils.localizedString("Clear")) { (action, indexPath) -> Void in
                
                self.tableView.beginUpdates()
                DownloadManager.sharedInstance.clearDownloadTask(indexPath.row)
                self.tableView.deleteRowsAtIndexPaths( [indexPath], withRowAnimation: UITableViewRowAnimation.Top)
                self.tableView.endUpdates()
             }
           
            clearAction.backgroundColor = LookAndFeel.style.clearBlueApple
            actions.append(clearAction)
            
        } else {
        
            if(downloadTask.isExecuting()){

                let restartAction = UITableViewRowAction(style: .Normal, title: Utils.localizedString("Pause")) { (action, indexPath) -> Void in
                    downloadTask.pauseDownload()
                    self.updateDownloadTaskCell(indexPath, downloadCell: nil)
                    self.tableView.editing = false
                }
                
                restartAction.backgroundColor = LookAndFeel.style.orangeApple
                actions.append(restartAction)


            } else if (downloadTask.isSuspended()){

                let restartAction = UITableViewRowAction(style: .Normal, title: Utils.localizedString("Resume")) { (action, indexPath) -> Void in
                    downloadTask.resumeDownload()
                    self.tableView.editing = false
                 }
                
                restartAction.backgroundColor = LookAndFeel.style.greenApple
                actions.append(restartAction)
        
            }
       
            let cancelAction = UITableViewRowAction(style: .Default, title: Utils.localizedString("Cancel")) { (action, indexPath) -> Void in
                tableView.editing = false
                
                let alert = UIAlertController(title: Utils.localizedString("Confirm action"), message: Utils.localizedString("Do you really want to cancel this process?"), preferredStyle: .Alert)
                
                alert.addAction(UIAlertAction(title: Utils.localizedString("No"), style: .Cancel, handler: nil))
                alert.addAction(UIAlertAction(title: Utils.localizedString("Yes"), style: .Destructive) { _ in
                    
                    self.tableView.beginUpdates()
                    DownloadManager.sharedInstance.clearDownloadTask(indexPath.row)
                    self.tableView.deleteRowsAtIndexPaths( [indexPath], withRowAnimation: UITableViewRowAnimation.Top)
                    self.tableView.endUpdates()
                    self.reloadData()
                })
                
                self.presentViewController(alert, animated: true, completion: nil)
            }
            
            actions.append(cancelAction)
            
        }
        
        return actions
    }
    
    func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
    }
 
    @IBAction func cancellActiveDownloads() {
    
        let alert = UIAlertController(title: Utils.localizedString("Confirm action"), message: Utils.localizedString("Do you really want to cancel all downloads?"), preferredStyle: .Alert)
        
        alert.addAction(UIAlertAction(title: Utils.localizedString("No"), style: .Cancel, handler: nil))
        alert.addAction(UIAlertAction(title: Utils.localizedString("Yes"), style: .Destructive) { _ in
            
            for downloadTask in DownloadManager.sharedInstance.listDownloads() {
                
                var indexesToClear:[Int] = []
                var downloadTasksToClear:[BackgroundDownloadTask] = []
                
                for (index, downloadTask) in enumerate(DownloadManager.sharedInstance.listDownloads()) {
                    
                    if(!downloadTask.isCompleted()) {
                        
                        indexesToClear.append(index)
                        downloadTasksToClear.append(downloadTask)
                    }
                }
                
                if(!indexesToClear.isEmpty) {
                    
                    self.tableView.beginUpdates()
                    
                    for index in indexesToClear {
                        
                        self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Top)
                    }
                    
                    for downloadTask in downloadTasksToClear {
                        
                        DownloadManager.sharedInstance.clearDownloadTask(downloadTask)
                    }
                    
                    self.tableView.endUpdates()
                    self.configureActionNavigationBar()
                }
            }
            self.reloadData()
        })
        
        self.presentViewController(alert, animated: true, completion: nil)
    }
    
    @IBAction func clearCompletedDownloads() {
     
        var indexesToClear:[Int] = []
        var downloadTasksToClear:[BackgroundDownloadTask] = []
        
        for (index, downloadTask) in enumerate(DownloadManager.sharedInstance.listDownloads()) {
            
            if(downloadTask.isCompleted()) {
              
                indexesToClear.append(index)
                downloadTasksToClear.append(downloadTask)
            }
        }
        
        if(!indexesToClear.isEmpty) {
            
            tableView.beginUpdates()
            
            for index in indexesToClear {
            
                tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Top)
            }
            
            for downloadTask in downloadTasksToClear {
                
                DownloadManager.sharedInstance.clearDownloadTask(downloadTask)
            }
            
            tableView.endUpdates()
            configureActionNavigationBar()
        }
        
    }
    
    override func viewWillAppear(animated: Bool) {
       
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateDownload:", name:"UpdateDownload", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "downloadFinished:", name:"FinishedDownload", object: nil)
        reloadData()
    }
    
    override func viewWillDisappear(animated: Bool) {
        
        NSNotificationCenter.defaultCenter().removeObserver(self, name:"UpdateDownload", object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name:"FinishedDownload", object: nil)
    }
    
    func titleForEmptyDataSet(scrollView:UIScrollView) -> NSAttributedString {
        
        let message = Utils.localizedString("No active downloads")
        return NSAttributedString(string: message, attributes: LookAndFeel.style.titleEmptyViewAttributes)
    }
    
    func descriptionForEmptyDataSet(scrollView:UIScrollView) -> NSAttributedString {
        
        let message = Utils.localizedString("There are not videos downloading at this moment")
        return NSAttributedString(string: message, attributes: LookAndFeel.style.descriptionEmptyViewAttributes)
    }
    
    func imageForEmptyDataSet(scrollView:UIScrollView) -> UIImage {
        
        return UIImage(named: "download-empty-state.png")!.imageByApplyingAlpha(0.7)
    }
    
    func redrawTitle(){
        
        var numActiveDownloads = 0
        
        for download in DownloadManager.sharedInstance.listDownloads() {
            
            if(download.isExecuting()) {
               
                numActiveDownloads++
            }
        }
        
        Async.main{
            
            self.subtitle = numActiveDownloads == 0 ? nil : Utils.localizedString("%d active", arguments: [numActiveDownloads])
        }
    }
    
    func reloadData(){
        
        tableView.reloadData()
        redrawTitle()
        configureActionNavigationBar()
    }
    
    func downloadFinished(notification: NSNotification){
    
        updateDownloadTaskCell(NSIndexPath(forRow: notification.object as Int, inSection: 0), downloadCell: nil)
        redrawTitle()
        configureActionNavigationBar()
    }
    
    func updateDownload(notification: NSNotification){
        
        updateDownloadTaskCell(NSIndexPath(forRow: notification.object as Int, inSection: 0), downloadCell: nil)
    }
    
    func updateDownloadTaskCell(index: NSIndexPath, var downloadCell: DownloadCell?) {
        
        if (downloadCell == nil){
            
            downloadCell = tableView.cellForRowAtIndexPath(index) as? DownloadCell
        }
        
        if let cell = downloadCell {
            
            let downloadTask = DownloadManager.sharedInstance.listDownloads()[index.row]
          
            Async.main {
            
                cell.progressBar.progress = Float(downloadTask.progress)
                cell.progressPercent.text = Utils.localizedString( "%.0f%%", arguments: [Float(downloadTask.progress) * 100.0])
                cell.downloadSize.text = Utils.localizedString("Downloading %.2f of %.2f MBs", arguments: [Float(downloadTask.numOfReadBytes)/1048576.0, Float(downloadTask.numOfExpectedBytes)/1048576.0])
                cell.estimateTimeFinish.text = Utils.formatSeconds(downloadTask.remainingSeconds)
            
                if(downloadTask.isSuspended()) {
                
                    cell.estimateTimeFinish.text = Utils.localizedString("Pause")
            
                } else if(downloadTask.isCompleted()){
                
                    cell.estimateTimeFinish.text = Utils.localizedString("Completed")
                }
            }
        }
        
        
    }
    
    func configureActionNavigationBar(){
        
        var areCompletedDownloads = false
        var areNotCompletedDownloads = false
     
        
        for download in DownloadManager.sharedInstance.downloads {
            
            if(download.isCompleted()) {
                
                areCompletedDownloads = true
            
            } else {
                
                areNotCompletedDownloads = true
            }
           
        }
        
        Async.main {
        
            self.cancelActiveDownloadsButton.enabled = areNotCompletedDownloads
            self.clearCompletedDownloadsButton.enabled = areCompletedDownloads
        }
    }
    
}

